package com.baidu.controller;

import com.baidu.entity.DeptBean;
import com.baidu.entity.PowerBean;
import com.baidu.entity.RoleBean;
import com.baidu.entity.UserBean;
import com.baidu.service.UserService;
import com.baidu.utils.Page;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 创作时间：2019/12/10 14:44
 * 作者：李增强
 */
@Controller
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 日期处理
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @RequestMapping("/getUserList")
    public String getStuList(Model model,HttpServletRequest request,UserBean ub,Date sbirthday,Date ebirthday,String yema){
        String contextPath = request.getContextPath();
        request.getSession().setAttribute("contextPath", contextPath);
        List<DeptBean> dlist = userService.getDeptList();
        /**
         * 先数数量（有模糊，数数量的时候，需要带着条件）
         */
        Integer count = userService.getUserCount(ub,sbirthday,ebirthday);
        Page page = new Page(yema, count, "3");
        List<UserBean> list = userService.getUserList(ub,sbirthday,ebirthday,page);
        model.addAttribute("list",list);
        model.addAttribute("ub", ub);
        model.addAttribute("sbirthday", sbirthday);
        model.addAttribute("ebirthday", ebirthday);
        model.addAttribute("page", page);
        model.addAttribute("dlist", dlist);
        return "user_list";
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @RequestMapping("/deleteUserById")
    public String deleteUserById(Integer id){
        userService.deleteUserById(id);
        return "redirect:getUserList.do";
    }

    /**
     * 去修改用户信息页面
     * @param ub
     * @param model
     * @return
     */
    @RequestMapping("/toUpdateUser")
    public String toUpdateUser(UserBean ub,Model model){
        ub = userService.getUserById(ub);
        model.addAttribute("ub", ub);
        return "user_update";
    }

    /**
     * 修改用户信息
     * @param
     * @return
     */
    @RequestMapping("/updateUser")
    public String updateUser(UserBean userBean,@Param("filename") MultipartFile filename, HttpServletRequest request){
        String filePath = request.getSession().getServletContext().getRealPath("");
        DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        String originalFilename = filename.getOriginalFilename();
        originalFilename = originalFilename.substring(originalFilename.lastIndexOf("."));
        String url = "/img/";
        url+=df.format(new Date())+"/"+UUID.randomUUID().toString()+originalFilename;
        filePath+=url;

        File file = new File(filePath);
        if(!file.exists()){
            new File(filePath).mkdirs();
        }

        if(!filename.isEmpty()){
            try {
                filename.transferTo(file);
                userBean.setUrl(url);
                userService.updateUser(userBean);
            }catch (Exception e){
            }
        }
        return "redirect:getUserList.do";
    }
    /**
     * 保存部门的角色
     */
    @RequestMapping("/saveDeptRole")
    public String saveDeptRole(Integer deptid,Integer[] rids){
        userService.saveDeptRole(deptid,rids);
        return "redirect:getDeptList.do";
    }


    /**
     * 去给部门分配角色，部门和角色的关系是一度对
     * 知道，部门的id，查询改部门的信息，
     * 查询出所有的角色列表
     * 页面需要回显，把部门原来的选中的角色回显出来
     * 怎么回显？
     */

    @RequestMapping("/toDeptRole")
    public String toDeptRole(Integer deptid, Model model){
        List<RoleBean> list = userService.getRoleList();
        List<Integer> rids = userService.getDeptRids(deptid);
        DeptBean db = userService.getDeptByDeptid(deptid);
        model.addAttribute("db", db);
        model.addAttribute("list", list);
        model.addAttribute("rids", rids);
        return "dept_role";
    }


    /**
     * 保存给用户分配的角色
     */
    @RequestMapping("/saveUserRole")
    public String saveUserRole(UserBean ub){
        userService.saveUserRole(ub);
        return "redirect:getUserList.do";
    }

    /**
     * 去给用户分配角色
     */
    @RequestMapping("/toUserRole")
    public String toUserRole(UserBean ub,Model model){
        ub = userService.getUserById(ub);
        List<RoleBean> list = userService.getDeptRoleList(ub);
        model.addAttribute("ub", ub);
        model.addAttribute("list", list);
        return "user_role";
    }


    /**
     * 保存给用户分配部门
     */
    @RequestMapping("/saveUserDept")
    public String saveUserDept(UserBean ub){
        userService.saveUserDept(ub);
        return "redirect:getUserList.do";
    }


    /**
     * 去给用户分配部门
     */
    @RequestMapping("/toUserDept")
    public String toUserDept(UserBean ub,Model model){
        List<DeptBean> list = userService.getDeptList();
        ub = userService.getUserById(ub);
        model.addAttribute("ub", ub);
        model.addAttribute("list", list);
        return "user_dept";
    }


    /**
     * 保存给角色分配的权限
     */
    @RequestMapping("/saveRolePower")
    public String saveRolePower(Integer rid,String ids){
        userService.saveRolePower(rid,ids);
        return "redirect:getRoleList.do";
    }


    /**
     * 去给角色分配权限页面
     */
    @RequestMapping("/toRolePower")
    public String toRolePower(Integer rid,Model model){
        List<PowerBean> list = userService.getPowerList(rid);
        JsonConfig jc = new JsonConfig();
        jc.setExcludes(new String[]{"url"});
        String json = JSONArray.fromObject(list,jc).toString();
        model.addAttribute("json", json);
        model.addAttribute("rid", rid);
        return "role_power";
    }


    /**
     *查看用户的权限
     */
    @RequestMapping("/getUserPower")
    public String getUserPower(Integer id,Model model){
        /**
         * 查看用户拥有的权限的时候，到了页面，点击菜单，原始菜单会跟着跳转，原因是用户的权限树里面的url有值
         * 解决方案：1、查看的sql里面直接不查询url就OK啦
         * 2、查出来不传递给他，在转化为json的时候，把url剔出去,net的jar包，alibb自己找找
         */
        List<PowerBean> list = userService.getUserPower(id);
        JsonConfig jc = new JsonConfig();
        jc.setExcludes(new String[]{"url"});
        String json = JSONArray.fromObject(list,jc).toString();

        model.addAttribute("json", json);
        return "user_power";
    }

    /**
     *查看部门的员工
     */
    @RequestMapping("/getDeptUser")
    public String getDeptUser(Integer deptid,Model model){
        DeptBean db = userService.getDeptByDeptid(deptid);
        model.addAttribute("db", db);
        return "dept_user";
    }

    /**
     *  查询部门列表
     */
    @RequestMapping("getDeptList")
    public String getDeptList(Model model){
        List<DeptBean> list = userService.getDeptList();
        model.addAttribute("list", list);
        return "dept_list";
    }

    /**
     *  查询角色列表
     */
    @RequestMapping("getRoleList")
    public String getRoleList(Model model){
        List<RoleBean> list = userService.getRoleList();
        model.addAttribute("list", list);
        return "role_list";
    }


    @RequestMapping("/getUserLogin")
    public String getUserLogin(UserBean userBean, HttpServletRequest request){
        UserBean rb = userService.getUserLogin(userBean);
        if(rb!=null){
            request.getSession().setAttribute("ub", rb);
            return "main";
        }
        return "../../index";
    }


    @RequestMapping("/saveUser")
    public String saveUser(UserBean userBean, @Param("filename") MultipartFile filename, HttpServletRequest request){



        //同样有10000万数据
        //告诉地址：img/aa.jpg，查找10000万次
        //另一个地址：/img/2019/12/16/aa.jpg，先找2019,100次，再找12,100次，再找16,100次，再找aa.jpg,需要400次
        //效率相差25万倍
        String filePath = request.getSession().getServletContext().getRealPath("");
        DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        String originalFilename = filename.getOriginalFilename();
        originalFilename = originalFilename.substring(originalFilename.lastIndexOf("."));
        String url = "/img/";
        url+=df.format(new Date())+"/"+UUID.randomUUID().toString()+originalFilename;
        filePath+=url;

        File file = new File(filePath);
        if(!file.exists()){
            new File(filePath).mkdirs();
        }

        if(!filename.isEmpty()){
            try {
                filename.transferTo(file);
                userBean.setUrl(url);
                userService.saveUser(userBean);
            }catch (Exception e){
            }
        }
        return "redirect:getUserList.do";
    }


    @RequestMapping("/toAddUser")
    public String toAddUser(){
        return "user_add";
    }



    @RequestMapping("/getPowerJson")
    public String getPowerJson(Model model,HttpServletRequest request){
        UserBean ub = (UserBean)request.getSession().getAttribute("ub");
        if(ub!=null){
            List<PowerBean> list = userService.getUserPower(ub.getId());
            String json = JSONArray.fromObject(list).toString();
            model.addAttribute("json", json);
        }
        return "left";
    }

}
